package com.hospital.hospitalsystem.modules.admin.biz;

import com.github.pagehelper.PageHelper;
import com.hospital.hospitalsystem.base.PageData;
import com.hospital.hospitalsystem.modules.admin.dao.entity.MedicalIntroduceEntity;
import com.hospital.hospitalsystem.modules.admin.dto.*;
import com.hospital.hospitalsystem.modules.admin.service.MedicalIntroduceService;
import com.hospital.hospitalsystem.modules.base.biz.UploadBiz;
import com.hospital.hospitalsystem.modules.base.dto.DeleteReq;
import com.hospital.hospitalsystem.modules.hospital.dao.entity.QuartzCronEntity;
import com.hospital.hospitalsystem.modules.hospital.service.QuartzCronService;
import com.hospital.hospitalsystem.modules.login.dao.entity.HospitalMessageEntity;
import com.hospital.hospitalsystem.modules.login.dao.entity.HospitalRegisterEntity;
import com.hospital.hospitalsystem.modules.login.dao.entity.UserEntity;
import com.hospital.hospitalsystem.modules.login.dto.EmailEntityExt;
import com.hospital.hospitalsystem.modules.login.service.HospitalMessageService;
import com.hospital.hospitalsystem.modules.login.service.HospitalRegisterService;
import com.hospital.hospitalsystem.modules.login.service.UserService;
import com.hospital.hospitalsystem.utils.SendEmailUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author qiancheng@cqxyy.net
 * @date 2023/2/22
 */
@Service
public class AdminBiz {

    @Autowired
    private UserService userService;

    @Autowired
    private HospitalMessageService hospitalMessageService;

    @Autowired
    private HospitalRegisterService hospitalRegisterService;

    @Autowired
    private QuartzCronService quartzCronService;

    @Autowired
    private MedicalIntroduceService medicalIntroduceService;

    @Autowired
    private UploadBiz uploadBiz;

    @Autowired
    private SendEmailUtils sendEmailUtils;
    /**
     * 查看申请医院列表
     * @param req
     * @return
     */
    public PageData<HospitalRegisterRsp> applyList(ApplyListReq req) {
        com.github.pagehelper.Page<HospitalRegisterRsp> page = PageHelper.startPage(
                req.getCurrentPage(), req.getPageSize()
        );
        Example example = new Example(HospitalRegisterEntity.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(req.getHospitalName())){
            criteria.andLike("name","%" + req.getHospitalName() + "%");
        }
        List<HospitalRegisterRsp> list = hospitalRegisterService.selectByExample(example).stream().map(s ->{
            HospitalRegisterRsp hospitalRegisterRsp = new HospitalRegisterRsp();
            BeanUtils.copyProperties(s,hospitalRegisterRsp);
            return hospitalRegisterRsp;
        }).collect(Collectors.toList());

        int longs = ((Number) page.getTotal()).intValue();
        PageData<HospitalRegisterRsp> pageData = PageData.of(list,page.getPageNum(),page.getPageSize(),longs);
        return pageData;
    }

    /**
     * 同意医院申请
     * @param req
     */
    @Transactional
    public void approvalApply(ApprovalApplyReq req) {
        Example example = new Example(HospitalRegisterEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("uuid",req.getUuid());
        HospitalRegisterEntity hospitalRegisterEntity = hospitalRegisterService.selectOneByExample(example);
        if (hospitalRegisterEntity == null){
            throw new RuntimeException("此条申请不存在");
        }
        EmailEntityExt emailEntityExt = new EmailEntityExt();
        String data = "尊敬的" + hospitalRegisterEntity.getManager() + "用户,您申请的" + hospitalRegisterEntity.getName() + "已验证通过，祝您使用愉快";
        String subject = "【中医诊所在线预约系统】-申请通过";
        emailEntityExt.setEmail(hospitalRegisterEntity.getEmail());
        emailEntityExt.setData(data);
        emailEntityExt.setSubject(subject);
        sendEmailUtils.sendEmails(emailEntityExt);
        HospitalMessageEntity hospitalMessageEntity = new HospitalMessageEntity();
        BeanUtils.copyProperties(hospitalRegisterEntity,hospitalMessageEntity);
        hospitalMessageEntity.setStatus(1);
        hospitalMessageEntity.setIssell(1);
        hospitalMessageService.insertSelective(hospitalMessageEntity);
        UserEntity user = new UserEntity();
        user.setType("hospital");
        user.setAccount(hospitalRegisterEntity.getEmail());
        user.setPassword(hospitalRegisterEntity.getPassword());
        user.setUuid(hospitalRegisterEntity.getUuid());
        userService.insertSelective(user);
        hospitalRegisterService.deleteByExample(example);
        //初始化定时任务
        QuartzCronEntity quartzCronEntity = new QuartzCronEntity();
        quartzCronEntity.setHospitalUuid(hospitalRegisterEntity.getUuid());
        quartzCronEntity.setStatus(1);
        quartzCronService.insertSelective(quartzCronEntity);
    }

    /**
     * 拒绝医院申请
     * @param req
     */
    public void reuseApply(ApprovalApplyReq req) {
        Example example = new Example(HospitalRegisterEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("uuid",req.getUuid());
        HospitalRegisterEntity hospitalRegisterEntity = hospitalRegisterService.selectOneByExample(example);
        if (hospitalRegisterEntity == null){
            throw new RuntimeException("此条申请不存在");
        }
        EmailEntityExt emailEntityExt = new EmailEntityExt();
        String data = "尊敬的" + hospitalRegisterEntity.getManager() + "用户,您申请的" + hospitalRegisterEntity.getName()
                + "拒绝通过，原因如下:\n" + req.getResult();
        String subject = "【中医诊所在线预约系统】-申请被拒绝";
        String email = hospitalRegisterEntity.getEmail();
        emailEntityExt.setEmail(email);
        emailEntityExt.setData(data);
        emailEntityExt.setSubject(subject);
        sendEmailUtils.sendEmails(emailEntityExt);
        hospitalRegisterService.deleteByExample(example);
    }

    /**
     * 新增药品介绍
     * @param req
     */
    public void medicalAdd(MedicalIntroduceReq req) {
        MedicalIntroduceEntity medicalIntroduceEntity = new MedicalIntroduceEntity();
        medicalIntroduceEntity.setName(req.getName());
        medicalIntroduceEntity.setUuid(UUID.randomUUID().toString());
        medicalIntroduceEntity.setPicture(req.getPicture());
        medicalIntroduceEntity.setPictureName(req.getPictureName());
        medicalIntroduceEntity.setIsotc(req.getIsOTC());
        medicalIntroduceEntity.setType(req.getType());
        medicalIntroduceEntity.setApprovalNumber(req.getApprovalNumber());
        medicalIntroduceEntity.setIntroduceHtml(StringEscapeUtils.unescapeHtml(req.getIntroduceHtml()));
        medicalIntroduceService.insertSelective(medicalIntroduceEntity);
    }

    /**
     * 检查药品名字是否重复
     * @param req
     * @return
     */
    public MedicalIntroduceCheckRsp medicalCheck(MedicalIntroduceReq req) {
        Example exampleMedicalIntroduce = new Example(MedicalIntroduceEntity.class);
        Example.Criteria criteriaMedicalIntroduce = exampleMedicalIntroduce.createCriteria();
        if (StringUtils.isNotEmpty(req.getName())) {
            criteriaMedicalIntroduce.andEqualTo("name",req.getName());
        }
        if (StringUtils.isNotEmpty(req.getApprovalNumber())) {
            criteriaMedicalIntroduce.andEqualTo("approvalNumber",req.getApprovalNumber());
        }
        if (StringUtils.isNotEmpty(req.getUuid())) {
            criteriaMedicalIntroduce.andNotEqualTo("uuid",req.getUuid());
        }
        List<MedicalIntroduceEntity> list = medicalIntroduceService.selectByExample(exampleMedicalIntroduce);
        MedicalIntroduceCheckRsp result = new MedicalIntroduceCheckRsp();
        result.setRepeat(CollectionUtils.isNotEmpty(list));
        return result;
    }

    /**
     * 删除药品介绍
     * @param req
     */
    public void medicalDelete(MedicalIntroduceReq req) {
        Example exampleMedicalIntroduce = new Example(MedicalIntroduceEntity.class);
        Example.Criteria criteriaMedicalIntroduce = exampleMedicalIntroduce.createCriteria();
        criteriaMedicalIntroduce.andEqualTo("uuid",req.getUuid());
        //从minio删除图片
        MedicalIntroduceEntity medicalIntroduceEntity = medicalIntroduceService.selectByExample(exampleMedicalIntroduce).get(0);
        DeleteReq deleteReq = new DeleteReq();
        List<String> objectName = new ArrayList<>();
        objectName.add(medicalIntroduceEntity.getName());
        deleteReq.setObjectName(objectName);
        deleteReq.setBucketName("medical-picture");
        uploadBiz.delete(deleteReq);
        medicalIntroduceService.deleteByExample(exampleMedicalIntroduce);
    }

    /**
     * 获取药品介绍
     * @param req
     * @return
     */
    public PageData<MedicalIntroduceRsp> medicalGet(MedicalIntroduceListReq req) {
        Example exampleMedicalIntroduce = new Example(MedicalIntroduceEntity.class);
        Example.Criteria criteriaMedicalIntroduce = exampleMedicalIntroduce.createCriteria();
        if (StringUtils.isNotEmpty(req.getName())) {
            criteriaMedicalIntroduce.andLike("name","%" + req.getName() + "%");
        }
        if (CollectionUtils.isNotEmpty(req.getIsOTC())) {
            criteriaMedicalIntroduce.andIn("isotc",req.getIsOTC());
        }
        if (req.getType() != null) {
            criteriaMedicalIntroduce.andEqualTo("type",req.getType());
        }
        if (StringUtils.isNotEmpty(req.getApprovalNumber())) {
            criteriaMedicalIntroduce.andEqualTo("approvalNumber",req.getApprovalNumber());
        }
        com.github.pagehelper.Page<HospitalRegisterRsp> page = PageHelper.startPage(
                req.getCurrentPage(), req.getPageSize()
        );
        List<MedicalIntroduceRsp> list = medicalIntroduceService.selectByExample(exampleMedicalIntroduce).stream().map(item -> {
            MedicalIntroduceRsp medicalIntroduceRsp = new MedicalIntroduceRsp();
            BeanUtils.copyProperties(item,medicalIntroduceRsp);
            medicalIntroduceRsp.setIsOTC(item.getIsotc());
            medicalIntroduceRsp.setIntroduceHtml(StringEscapeUtils.escapeHtml(item.getIntroduceHtml()));
            return medicalIntroduceRsp;
        }).collect(Collectors.toList());
        int longs = ((Number) page.getTotal()).intValue();
        PageData<MedicalIntroduceRsp> pageData = PageData.of(list,page.getPageNum(),page.getPageSize(),longs);
        return pageData;
    }

    /**
     * 更新药品介绍
     * @param req
     */
    public void medicalUpdate(MedicalIntroduceReq req) {
        Example exampleMedicalIntroduce = new Example(MedicalIntroduceEntity.class);
        Example.Criteria criteriaMedicalIntroduce = exampleMedicalIntroduce.createCriteria();
        criteriaMedicalIntroduce.andEqualTo("uuid",req.getUuid());
        MedicalIntroduceEntity medicalIntroduceEntity = new MedicalIntroduceEntity();
        medicalIntroduceEntity.setIntroduceHtml(StringEscapeUtils.unescapeHtml(req.getIntroduceHtml()));
        medicalIntroduceEntity.setPicture(req.getPicture());
        medicalIntroduceEntity.setPictureName(req.getPictureName());
        medicalIntroduceEntity.setName(req.getName());
        medicalIntroduceEntity.setIsotc(req.getIsOTC());
        medicalIntroduceEntity.setType(req.getType());
        medicalIntroduceEntity.setApprovalNumber(req.getApprovalNumber());
        medicalIntroduceService.updateByExampleSelective(medicalIntroduceEntity,exampleMedicalIntroduce);
    }

    /**
     * 根据药品uuid获取信息
     * @param req
     * @return
     */
    public MedicalIntroduceRsp medicalGetOne(MedicalIntroduceReq req) {
        Example exampleMedicalIntroduce = new Example(MedicalIntroduceEntity.class);
        Example.Criteria criteriaMedicalIntroduce = exampleMedicalIntroduce.createCriteria();
        criteriaMedicalIntroduce.andEqualTo("uuid",req.getUuid());
        MedicalIntroduceEntity medicalIntroduceEntity = medicalIntroduceService.selectByExample(exampleMedicalIntroduce).get(0);
        MedicalIntroduceRsp medicalIntroduceRsp = new MedicalIntroduceRsp();
        BeanUtils.copyProperties(medicalIntroduceEntity,medicalIntroduceRsp);
        medicalIntroduceRsp.setIsOTC(medicalIntroduceEntity.getIsotc());
        medicalIntroduceRsp.setIntroduceHtml(StringEscapeUtils.escapeHtml(medicalIntroduceEntity.getIntroduceHtml()));
        return medicalIntroduceRsp;
    }
}
